using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class Object_Merchant : Object_NPC
{
    public Inventory_Player playerInventory { get; private set; }
    private Inventory_Merchant merchant;
    protected override void Awake()
    {
        base.Awake();
        merchant = GetComponent<Inventory_Merchant>();
    }
    protected override void OnEnable()
    {
        base.OnEnable();
        questManager.OnQuestFinish += RemoveQuest;
    }
    protected override void Update()
    {
        base.Update();
        if (Input.GetKeyDown(KeyCode.Z))
            merchant.UpdateStore();
    }
    public override void Interact()
    {
        base.Interact();
        // uI.OpenQuestUI(questDatas);
        merchant.SetInventoryPlayer(playerInventory);
        uI.merchantUI.SetupMerchantUI(playerInventory, merchant);
        uI.OpenDialogueUI(dialogueLine, new DialogueNPCData(rewardNPC, questDatas));
        // uI.OpenMerchantUI(true);
    }

    protected override void OnTriggerEnter2D(Collider2D collision)
    {
        base.OnTriggerEnter2D(collision);
        playerInventory = player?.GetComponent<Inventory_Player>();
    }

    protected override void OnTriggerExit2D(Collider2D collision)
    {
        base.OnTriggerExit2D(collision);

        uI.OpenMerchantUI(false);
    }

    private void RemoveQuest(QuestData questData)
    {
        List<QuestDataSO> questDataList = questDatas.ToList();
        questDataList.Remove(questData.questDataSO);

        questDatas = questDataList.ToArray();
    }
    public override void SaveData(ref GameData gameData)
    {
        gameData.merchantQuests.Clear();
        for (int i = 0; i < questDatas.Length; i++)
            gameData.merchantQuests.Add(questDatas[i].questSaveId);
    }
    public override void LoadData(GameData gameData)
    {
        if (gameData.merchantQuests.Count == 0)
            return;
            
        QuestDataBaseSO questDataBaseSO = questManager.questDataBaseSO;
        List<QuestDataSO> questDataList = new();
        for (int i = 0; i < gameData.merchantQuests.Count; i++)
        {
            string questId = gameData.merchantQuests[i];
            QuestDataSO questDataSO = questDataBaseSO.GetQuestById(questId);

            if (questDataSO == null)
                continue;
            questDataList.Add(questDataSO);
        }
        questDatas = questDataList.ToArray();
    }
}
